<template>
  <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
    <el-form-item label="直播ID" prop="liveId">
      <el-input placeholder="请询问直播管理员获取" v-model="ruleForm.liveId"></el-input>
    </el-form-item>
    <el-form-item label="用户昵称">
      <el-input placeholder="不填写则随机" v-model="ruleForm.username"></el-input>
    </el-form-item>
    <el-form-item label="用户头像">
      <el-input placeholder="不填写则随机" v-model="ruleForm.avatar"></el-input>
    </el-form-item>

    <el-form-item label="评论" prop="contents">
      <el-input placeholder="一行一条，不要输入特殊字符" rows="6" resize="none" type="textarea" v-model="ruleForm.contents"></el-input>
      <span id="testSpanForCheck" style="visibility:hidden"></span>
    </el-form-item>
    <el-form-item label="用户类型">
      <el-radio-group v-model="ruleForm.sex">
        <el-radio :label="3">男女混合</el-radio>
        <el-radio :label="1">男</el-radio>
        <el-radio :label="2">女</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="时间间隔">
      <el-select v-model="ruleForm.timeSpace" placeholder="请选择间隔时间">
        <el-option v-for="item in ruleForm.timeSpaceArr" :key="item.value" :label="item.label" :value="item.value"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item class="options-button">
      <el-button v-if="!submitTask" icon="el-icon-position" type="primary" @click="submitForm('ruleForm')">提交任务</el-button>
      <el-button v-if="submitTask" icon="el-icon-switch-button" @click="stopTask" type="danger">停止任务</el-button>
      <el-button icon="el-icon-open" @click="alertLivePage">打开直播</el-button>
      <el-button icon="el-icon-s-operation" @click="showTaskLists">任务列表</el-button>
      <el-button icon="el-icon-menu" @click="alertAboutWindow">更多</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import {ipcRenderer} from "electron";
import {LIVE_URL} from "@/utils/define";
import {getUser, parseContent, randomNum, sleep} from "@/utils/electron";
import {allData,female,male} from '@/data/sex.js'
import request from "@/utils/request";
import schedule from 'node-schedule'
import qs from "qs";
import DataStore from "@/utils/DataStore";


export default {
  name: "CreateTaskForm",
  data() {
    return {
      myStore:null,
      submitTask:false,
      schedule:null,
      contentIndex:0,
      contentsArr:[],
      ruleForm: {
        liveId: "",
        username: '',
        avatar:"",
        sex: 3,
        timeSpace:1,
        timeSpaceArr:[
          {
            value: 1,
            label: '每条间隔1秒'
          }, {
            value: 2,
            label: '每条间隔2秒'
          }, {
            value: 3,
            label: '每条间隔3秒'
          }, {
            value: 4,
            label: '每条间隔4秒'
          }, {
            value: 5,
            label: '每条间隔5秒'
          }
        ],
        contents: '',
      },
      rules: {
        liveId: [
          { required: true, message: '请输入直播ID', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        contents: [
          { required: true, message: '请填写评论', trigger: 'blur' }
        ]
      }
    };
  },
  mounted() {
    this.myStore = new DataStore({name:'taskListsData'});
  },
  methods: {
    showTaskLists(){
      this.$emit('showTaskLists',{})
    },
    alertAboutWindow(){
      ipcRenderer.send('open-about-window','about')
    },
    createTaskLists(contentArr){
      let _this = this;
      console.log("new Date().getTime()",new Date().getTime())
      //添加记录任务列表
     _this.myStore.addTracks({liveId:_this.ruleForm.liveId,ctime:new Date().getTime(),contents:JSON.stringify(contentArr),status:1})
    },
    alertLivePage(){
      let _this = this;
      if(_this.ruleForm.liveId != ""){
        ipcRenderer.send('open-live-window-by-id',LIVE_URL+_this.ruleForm.liveId)
      } else {
        _this.$message.error('请输入直播ID');
      }
    },
    sendComment(content,user){
      let _this = this;
      if(content === undefined){
        _this.stopTask();
        _this.$notify({title: '成功', message: '任务执行完毕', type: 'success'});
      } else {
        request.post('/huodong/sj/el/yszlive.php',{
          data:qs.stringify({
            liveID:_this.ruleForm.liveId,
            message:content,
            username:user[0],
            avatar:user[1]
          }),
          headers:{
            Authorization:"Bearer pojroewtoe2d6vr93bxpf89kf1656qy4",
            "content-type": "application/x-www-form-urlencoded",
          }
        }).then( res => {
          if(res.code === 1 ){
            _this.$store.dispatch('changeLogs', {type: 'SUCCESS', desc: '['+content+'].response time:'+new Date().getTime()})
          }
        }).catch(error => {
          console.log(error)
          _this.$store.dispatch('changeLogs', {type: 'FAILED', desc: '['+content+'].response time:'+new Date().getTime()})
        })
      }
    },
    stopTask(){
      console.log('stop task')
      let _this = this;
      _this.schedule.cancel();
      _this.schedule = null;
      _this.submitTask = false;
      _this.contentIndex = 0;
    },
    submitForm(formName) {
      let _this = this;
      _this.$refs[formName].validate((valid) => {
        if (valid) {
          //是否输入了昵称或者头像
          _this.submitTask = true
          _this.$notify({title: '成功', message: '任务创建成功', type: 'success'});
          let userData = _this.ruleForm.sex == 1 ? male : _this.ruleForm.sex == 3 ? allData : female
          let contentArr = parseContent(this.ruleForm.contents).map(content => {
              return content
          }).filter(content => content !== "")
          _this.schedule = schedule.scheduleJob("*/"+_this.ruleForm.timeSpace+" * * * * ?", function(){
            let random = randomNum(0,userData.length,false)
            let user = getUser(userData[random]);
            user[0] = _this.ruleForm.username  ?  _this.ruleForm.username : user[0]
            user[1] = _this.ruleForm.avatar ? _this.ruleForm.avatar :user[1]
            _this.sendComment(contentArr[_this.contentIndex++],user)
          });
          _this.createTaskLists(contentArr)
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      //this.$refs[formName].resetFields();
    }
  }
}
</script>

<style scoped>
.el-form{
  padding: 20px 0px 0px 0px;
}
.el-form .el-form-item.options-button{
  margin-bottom:10px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-around;
  align-items: center;
  align-content: center;
}
.el-form .el-form-item ~ textarea{
  width: 100%;
  height: 100%;
}
</style>
